package com.kehongborui.fliggy.service.impl;

import com.kehongborui.fliggy.entity.OrderDetail;
import com.kehongborui.fliggy.entity.OrderMaster;
import com.kehongborui.fliggy.entity.PassStation;
import com.kehongborui.fliggy.entity.Vehicle;
import com.kehongborui.fliggy.enums.OrderStatus;
import com.kehongborui.fliggy.exception.FliggyException;
import com.kehongborui.fliggy.mapper.OrderDetailMapper;
import com.kehongborui.fliggy.mapper.OrderMasterMapper;
import com.kehongborui.fliggy.mapper.PassStationMapper;
import com.kehongborui.fliggy.mapper.VehicleMapper;
import com.kehongborui.fliggy.model.OrderMasterModel;
import com.kehongborui.fliggy.model.OrderModel;
import com.kehongborui.fliggy.model.PassengerModel;
import com.kehongborui.fliggy.service.OrderService;
import com.kehongborui.fliggy.util.CommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.kehongborui.fliggy.enums.ExceptionMessage.SEATS_AMOUNT_ERROR;
import static com.kehongborui.fliggy.enums.PayStatus.WAIT;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-22
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private PassStationMapper passStationMapper;
    @Autowired
    private VehicleMapper vehicleMapper;
    @Autowired
    private OrderMasterMapper orderMasterMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional
    public OrderModel create(OrderModel orderModel) {
        // 确认余票的数量（判断库存：stock）
        Integer seatsAmount = vehicleMapper.getSeatsAmount(orderModel.getVehicleNo());
        if (seatsAmount - orderModel.getPassengerModelList().size() < 0) {
            throw new FliggyException(String.format(SEATS_AMOUNT_ERROR.getDesc(), orderModel.getVehicleNo()));
        }

        // 第一步：算总价，先确认车次，座位等级（本项目没有使用），起始站，重点站
        List<Integer> seqs = passStationMapper.findPassStationById(
                Arrays.asList(orderModel.getDepStation(), orderModel.getArrStation()));

        // 用户购票的总价格
        long totalPrice = (passStationMapper.totalPrice(seqs.get(0), seqs.get(1), orderModel.getVehicleId()))
                * orderModel.getPassengerModelList().size();

        // 第二步：保存主订单
        OrderMaster orderMaster = new OrderMaster();

        orderMaster.setPrice((int)totalPrice);
        BeanUtils.copyProperties(orderModel, orderMaster);
        orderMaster.setOrderId(CommonUtils.generateOrderId());
        orderMaster.setCreateTime(new Date());
        orderMaster.setOrderStatus(OrderStatus.NEW.getCode());
        orderMaster.setPayStatus(WAIT.getCode());
        int ret = orderMasterMapper.insertSelective(orderMaster);

        // 第三步：保存订单详情（子订单）
        orderModel.getPassengerModelList().stream().forEach(passengerModel -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(passengerModel, orderDetail);
            orderDetail.setOrderId(orderMaster.getOrderId());
            orderDetail.setPassengerName(passengerModel.getName());
            orderDetail.setCreateTime(new Date());
            // 保存订单详情：法一：每条详情单独保存，法二：所有详情一次性保存
            orderDetailMapper.insertSelective(orderDetail);
        });

        // 扣库存
        Vehicle vehicle = new Vehicle();
        vehicle.setId(orderModel.getVehicleId());
        // 修改库存数量
        vehicle.setSeatsAmount(seatsAmount - orderModel.getPassengerModelList().size());
        vehicleMapper.updateByPrimaryKeySelective(vehicle);

        orderModel.setOrderId(orderMaster.getOrderId());
        orderModel.setPayStatus(orderMaster.getPayStatus());
        orderModel.setBuyerUid(orderMaster.getBuyerUid());
        orderModel.setOrderStatus(orderMaster.getOrderStatus());
        orderModel.setOrderAmount(orderMaster.getOrderAmount());
        orderModel.setPrice(totalPrice);
        return orderModel;
    }

    @Override
    public boolean cancel(String buyerUid, String orderId) {
        return false;
    }

    @Override
    public OrderModel findById(String orderId) {
        // 查询主订单
        OrderMaster orderMaster = orderMasterMapper.selectByPrimaryKey(orderId);
        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderMasterId(orderId);

        OrderModel model = new OrderModel();
        BeanUtils.copyProperties(orderMaster, model);

        List<PassengerModel> passengerModels = orderDetailList.stream().map(o -> {
            PassengerModel passengerModel = new PassengerModel();
            BeanUtils.copyProperties(o, passengerModel);
            passengerModel.setName(o.getPassengerName());
            return passengerModel;
        }).collect(Collectors.toList());

        model.setPrice(orderMaster.getPrice().longValue());
        model.setPassengerModelList(passengerModels);

        return model;
    }

    @Override
    public List<OrderMasterModel> findAll() {
        return null;
    }

    @Override
    public boolean paid(OrderModel orderModel) {
        return false;
    }
}
